package com.usiful.util;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

import com.usiful.model.Attachment;
import com.usiful.model.EmailContext;
import com.usiful.schema.UsifulConfigSchema;

/**
 * 
 * @author [周织能]
 * @description  邮件发送工具
 * @date 2016年7月30日
 * @email 742408364@qq.com
 */
public class UsifulEmailHelper {

	public static void send2Yami() {;
	        EmailContext emailCtx = new EmailContext();
	        emailCtx.setHost("smtp.163.com");
	        emailCtx.setPort(465);
	        emailCtx.setFrom("jnetzhou@163.com");
	        emailCtx.setTo("524451037@qq.com");
	        emailCtx.setUsername("jnetzhou");
	        emailCtx.setPassword("jnetzhou1989");
	        emailCtx.setSubject("跟卖数据");
	        emailCtx.setContent("跟卖数据带附件");
	        Set<Attachment> attachments = new HashSet<Attachment>();
	        Attachment attachment1 = new Attachment();
	        attachment1.setPath(UsifulConfigSchema.RESULT_FILE);
	        attachment1.setName(UsifulConfigSchema.RESULT_FILE.replace(UsifulConfigSchema.SAVE_PATH, ""));
	        attachment1.setDescription("跟卖数据");
	        attachments.add(attachment1);
	        emailCtx.setAttachments(attachments);
	        sendEmail(emailCtx);
	}
	
	
	/**
	 * 发送邮件，可带附件
	 * @param emailCtx
	 */
	public static void sendEmail(EmailContext emailCtx) {
        boolean isSSL = true;
        try {
        	MultiPartEmail email = new MultiPartEmail();
            email.setSSLOnConnect(isSSL);
            email.setHostName(emailCtx.getHost());
            email.setSmtpPort(emailCtx.getPort());
            email.setAuthentication(emailCtx.getUsername(), emailCtx.getPassword());
            email.setFrom(emailCtx.getFrom());
            email.addTo(emailCtx.getTo());
            email.setSubject(emailCtx.getSubject());
            email.setMsg(emailCtx.getContent());
            if(emailCtx.getAttachments() != null) {
            	Set<Attachment> attachments = emailCtx.getAttachments();
            	for(Attachment attachment : attachments) {
            		EmailAttachment emailAttachment = new EmailAttachment();
            		emailAttachment.setDisposition(EmailAttachment.ATTACHMENT);
            		emailAttachment.setName(attachment.getName());
            		emailAttachment.setPath(attachment.getPath());
            		emailAttachment.setDescription(attachment.getDescription());
            		email.attach(emailAttachment);
            	}
            	
            }
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }

        System.out.println("发送完毕！");
    }

}
